﻿using System;

using System.Threading;

namespace BGM.Sensors.MeasuringDevice
{
    public class Watchdog
    {
       public delegate void ErrorMethod();
        ErrorMethod errorMethod;
        // Notifies a waiting thread that an event has occurred
        AutoResetEvent evnt = new AutoResetEvent(false);
        TimeSpan timeOut;
        public Watchdog(TimeSpan timeout, ErrorMethod errorMethod)
        {
            this.errorMethod = errorMethod;
            this.timeOut = timeout;
        }
        public void Start()
        {

            Thread th = new Thread(new ThreadStart(waitForTimeOut));
            // Sets the state of the specified event to non signaled.
            evnt.Reset();
            th.IsBackground = true;
            // start thread
            th.Start();
           
        }
        void waitForTimeOut()
        {
           
            if (evnt.WaitOne(timeOut, false))
                // Sucess - timeout did not occurred
                return;
            else
            {
               
                if (errorMethod != null)
                    errorMethod();
            }
        }
        public void Signal()
        {
            evnt.Set();
        }
    }
}
